package ysf.com.mediumdifficulty;

/**
 * 三十三
 * 在数组中找到目标值并返回下标值
 *
 * @author ysf
 * @date 2021/8/19 15:26
 */
public class ThirtyThreeDemo {

    public static void main(String[] args) {

        int[] nums = new int[]{4, 5, 6, 7, 0, 1, 2};
        int traget = 2;

        /*int search = search(nums, traget);
        System.out.println(search);*/

        int searchs = searchs(nums, traget);
        System.out.println(searchs);
    }

    public static int search(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == target) {
                return i;
            }
        }
        return 0;
    }

    public static int searchs(int[] nums, int target) {
        int lo = 0, hi = nums.length - 1;
        while (lo <= hi) {
            int mid = lo + (hi - lo) / 2;
            int num = nums[mid];
            //nums [ mid ] 和 target 在同⼀段
            if ((nums[mid] < nums[0]) == (target < nums[0])) {
                num = nums[mid];
                //nums [ mid ] 和 target 不在同⼀段，同时还要考虑下变成 -inf 还是 inf。
            } else {
                num = target < nums[0] ? Integer.MIN_VALUE : Integer.MAX_VALUE;
            }
            if (num < target) {
                lo = mid + 1;
            } else if (num > target) {
                hi = mid - 1;
            } else {
                return mid;
            }
        }
        return -1;
    }


}
